package com.wangan;

import com.lowagie.text.pdf.BaseFont;
import jdk.nashorn.internal.runtime.regexp.JoniRegExp;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.xhtmlrenderer.extend.FontResolver;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // 获取 java 版本
        String version = System.getProperty("java.specification.version");

        // 获取系统类型
        String platform = System.getProperty("os.name", "");
        platform = platform.toLowerCase().contains("window") ? "win" : "linux";

        // 当前程序目录
        String current = System.getProperty("user.dir");

        System.out.println(String.format("current=%s", current));

        // html 文件路径
        File index = Paths.get(current, "..", "index.html").toFile();
        if (!index.exists()) {
            System.out.println(String.format("file not exist,file=%s", index.getAbsolutePath()));
            return;
        }

        try {
            Document document = Jsoup.parse(index, "UTF-8");
            // 补全标记
            document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);

            ITextRenderer render = new ITextRenderer();
            ITextFontResolver fontResolver = render.getFontResolver();

            File[] fonts = Paths.get(current, "..", "fonts").toFile().listFiles();
            for (File item : fonts) {
                // 应该这样添加字体
                fontResolver.addFont(item.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }

            SharedContext sharedContext = render.getSharedContext();
            sharedContext.setPrint(true);
            sharedContext.setInteractive(false);
            sharedContext.getTextRenderer().setSmoothingThreshold(0);

            // 自定义图片解析
            // sharedContext.setReplacedElementFactory(new ReplacedElementFactoryImpl());

            // 指定根目录,这里需要 URL 格式
            // file:/D:/work/linux-html2pdf-demo/openpdf-demo/../
            String baseUrl = Paths.get(current, "..").toUri().toURL().toString();
            render.setDocumentFromString(document.html(), baseUrl);
            render.layout();

            File file = Paths.get(current, String.format("java%s_%s.pdf", version, platform)).toFile();
            FileOutputStream stream = new FileOutputStream(file);
            render.createPDF(stream);
            stream.close();

            System.out.println(String.format("file=%s", file.getAbsolutePath()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}